#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "Thread.hpp"
#include "comm.h"
#include "InetAddr.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage:\n\t" << proc << " server_ip server_port\n"
              << std::endl;
}

struct ThreadData
{
    ThreadData(int sockfd, InetAddr addr) : _sockfd(sockfd),
                                            _addr(addr)
    {
    }

    ~ThreadData()
    {
    }

    int _sockfd;
    InetAddr _addr;
};

void Recv(const ThreadData& td)
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        size_t m = recvfrom(td._sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl;
        }
        else
            break;
    }
}

void Send(ThreadData& td)
{
    while(true)
    {
        std::string inbuffer;
        std::cout << "Please Enter# ";
        getline(std::cin, inbuffer);
        auto server = td._addr.GetAddr();
        socklen_t len = sizeof(server);
        int n = sendto(td._sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, len);
        if(n <= 0)
        {
            std::cout << "Send message failed!" << std::endl;
            break;
        }
    }
}
// 为什么客户端也要改成多线程？
// 因为如果按照单线程来，客户端必须向服务器发消息后，才能看到其他用户发的消息
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(usageError);
    }
    // 通过用户输入获取服务器的ip和port
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建套接字文件
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "Sock Error: " << strerror(errno) << std::endl;
        exit(sockError);
    }
    std::cout << "Sock Success" << std::endl;

    // 客户端并不需要显式绑定

    // 填充服务器网络地址类型结构体，在向服务器发送数据时要用到
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    InetAddr serverAddr(server);

    ThreadData td(sockfd, serverAddr);
    Thread<ThreadData> Sender("send", Send, td);
    Thread<ThreadData> Receiver("receive", Recv, td);
    Sender.Start();
    Receiver.Start();

    Sender.Join();
    Receiver.Join();

    close(sockfd);
    return 0;
}